from django.shortcuts import render
from django.views.generic import View
from users.models import UserProfile, onceName, notice
from treehole.models import secret, comment, agree
from .models import chatRoom, chatRecord
from utils.mixin_utils import LoginRequiredMixin, get_current_ip
import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket,require_websocket

BUF_SIZE = 1024
host = 'localhost'
port = 8081

# Create your views here.


class getNewsViews(LoginRequiredMixin, View):
    # 用户信息与通知
    def get(self, request):
        if not request.user:
            resjson = {
                "ret": True,
                "status": "notLogin",
                "msg": "用户未登录"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')

        # 寻找全部和当前用户有关的聊天记录
        onceNameOneModels = chatRoom.objects.filter(onceNameOne__user__id=int(request.user.id), isDelete=False)
        onceNameTwoModels = chatRoom.objects.filter(onceNameTwo__user__id=int(request.user.id), isDelete=False)
        # 互动通知
        InteractionNotice = notice.objects.filter(user__id=int(request.user.id), noticeType__id=int(1), isDelete=False)
        # 系统通知
        systemNotice = notice.objects.filter(noticeType__id=int(2), isDelete=False)

        onceNameOneLen = len(onceNameOneModels) - 1
        onceNameTwoLen = len(onceNameTwoModels) - 1
        chat = []
        for onceNameOneLi in onceNameOneModels:
            chatRecordLi = chatRecord.objects.filter(chatRoom__id=int(onceNameOneLi.id))
            chatRecordLiLen = len(chatRecordLi) - 1
            LastChatRecordLi = chatRecordLi[chatRecordLiLen]
            chat.append({
                "treeHoleId": LastChatRecordLi.chatRoom.secret.treeHole.id,
                "treeHoleName": LastChatRecordLi.chatRoom.secret.treeHole.title,
                "chatId": LastChatRecordLi.chatRoom.id,
                "name": LastChatRecordLi.chatRoom.onceNameOne.name,
                "userId": LastChatRecordLi.chatRoom.onceNameOne.user.id,
                "userSex": LastChatRecordLi.chatRoom.onceNameOne.user.sex,
                "content": LastChatRecordLi.content,
                "Datetime": str(LastChatRecordLi.time)
            })

        for onceNameTwoLi in onceNameTwoModels:
            chatRecordLi = chatRecord.objects.filter(chatRoom__id=int(onceNameTwoLi.id))
            chatRecordLiLen = len(chatRecordLi) - 1
            LastChatRecordLi = chatRecordLi[chatRecordLiLen]
            chat.append({
                "treeHoleId": LastChatRecordLi.chatRoom.secret.treeHole.id,
                "treeHoleName": LastChatRecordLi.chatRoom.secret.treeHole.title,
                "chatId": LastChatRecordLi.chatRoom.id,
                "name": LastChatRecordLi.chatRoom.onceNameTwo.name,
                "userId": LastChatRecordLi.chatRoom.onceNameTwo.user.id,
                "userSex": LastChatRecordLi.chatRoom.onceNameTwo.user.sex,
                "content": LastChatRecordLi.content,
                "Datetime": str(LastChatRecordLi.time)
            })


        if len(systemNotice) == 0:
            system = {}
        else:
            system = {
                "name": systemNotice[len(systemNotice)-1].noticeType.type,
                "content": systemNotice[len(systemNotice)-1].noticeContent,
                "Datetime": str(systemNotice[len(systemNotice)-1].time)
            }

        if len(InteractionNotice) == 0:
            Interaction = {}
        else:
            Interaction = {
                "name": InteractionNotice[len(InteractionNotice)-1].noticeType.type,
                "content": InteractionNotice[len(InteractionNotice)-1].noticeContent,
                "Datetime": str(InteractionNotice[len(InteractionNotice)-1].time)
            }

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "chat": chat,
                "Interaction": Interaction,
                "system": system
            }
        }
        return HttpResponse(json.dumps(resjson), content_type='application/json')




class getChatIdViews(LoginRequiredMixin, View):
    # 根据聊天房间ID查询聊天记录
    def get(self, request):
        if not request.user:
            resjson = {
                "ret": True,
                "status": "notLogin",
                "msg": "用户未登录"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')

        id = request.GET.get('id')

        chatRecordModels = chatRecord.objects.filter(chatRoom__id=int(id), isDelete=False)
        try:
            chatRoomModels = chatRoom.objects.get(id=int(id), isDelete=False)
        except chatRoom.DoesNotExist:
            resjson = {
                "ret": True,
                "status": "fail",
                "msg": "聊天室不存在"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')

        chat = []
        findUser = False
        for chatRecordLi in chatRecordModels:
            # 获取当前用户聊天时使用的曾用名
            # 获取当前用户
            # 获取聊天室两个用户
            # 与当前用户相同的为
            if not findUser:
                if request.user.id == chatRecordLi.chatRoom.onceNameOne.user.id:
                    chatRoomUser = chatRecordLi.chatRoom.onceNameOne
                else:
                    chatRoomUser = chatRecordLi.chatRoom.onceNameTwo
                findUser = True

            chat.append({
                "currentUser": 1 if request.user.id == chatRecordLi.currentUser.id else 0,
                "text": chatRecordLi.content,
                "time": str(chatRecordLi.time)
            })


        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "newData": str(chatRecordModels[0].chatRoom.secret.time),
                "userId": chatRoomUser.user.id,
                "userName": chatRoomUser.name,
                "secret": {
                    "id": chatRecordModels[0].chatRoom.secret.id,
                    "userId": chatRecordModels[0].chatRoom.secret.onceName.user.id,
                    "treeHoleId": chatRecordModels[0].chatRoom.secret.treeHole.id,
                    "treeHoleName": chatRecordModels[0].chatRoom.secret.treeHole.title,
                    "content": chatRecordModels[0].chatRoom.secret.content,
                    "dateTime": str(chatRecordModels[0].chatRoom.secret.time)
                },
                "chat": chat
            }
        }

        return HttpResponse(json.dumps(resjson), content_type='application/json')


class getInterViews(LoginRequiredMixin, View):
    # 获取所有互动通知
    def get(self,request):
        # 互动通知
        InteractionNotice = notice.objects.filter(user__id=int(request.user.id), noticeType__id=int(1), isDelete=False)
        Read = []
        for InteractionNoticeLi in InteractionNotice:
            commentUl = comment.objects.filter(secret__id=int(InteractionNoticeLi.secretModel.id))
            agreeUl = agree.objects.filter(secret__id=int(InteractionNoticeLi.secretModel.id))
            if InteractionNoticeLi.replyModel:
                reply = InteractionNoticeLi.replyModel.content
            else:
                reply = ""
            Read.append({
                "operation": InteractionNoticeLi.noticeContent,
                "CommentAndSelect": 1,
                "reply": reply,
                "select": {
                    "id": InteractionNoticeLi.secretModel.id,
                    "userId": InteractionNoticeLi.secretModel.onceName.user.id,
                    "treeHoleId": InteractionNoticeLi.secretModel.treeHole.id,
                    "treeHoleName": InteractionNoticeLi.secretModel.treeHole.title,
                    "content": InteractionNoticeLi.secretModel.content,
                    "liveNum": len(agreeUl),
                    "commentNum": len(commentUl),
                    "dateTime": str(InteractionNoticeLi.secretModel.time)
                },
                "dateTime": str(InteractionNoticeLi.time)
            })

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "Read": Read
            }
        }

        return HttpResponse(json.dumps(resjson), content_type='application/json')


class getSystemViews(LoginRequiredMixin, View):
    # 获取所有系统通知
    def get(self,request):
        # 系统通知
        SystemNotice = notice.objects.filter(noticeType__id=int(2), isDelete=False)
        system = []
        for SystemNoticeLi in SystemNotice:
            if SystemNoticeLi.replyModel:
                reply = SystemNoticeLi.replyModel.content
            else:
                reply = ""
            if SystemNoticeLi.topicofcModel:
                topicofc = {
                    "id": SystemNoticeLi.topicofcModel.id,
                    "treeHoleId": SystemNoticeLi.topicofcModel.treeHole.id,
                    "treeHoleName": SystemNoticeLi.topicofcModel.treeHole.title,
                    "content": SystemNoticeLi.topicofcModel.content,
                    "dateTime": str(SystemNoticeLi.topicofcModel.time)
                }
            else:
                topicofc = {}
            system.append({
                "operation": SystemNoticeLi.noticeContent,
                "CommentAndSelect": 1,
                "reply": reply,
                "topicofc": topicofc,
                "dateTime": str(SystemNoticeLi.time)
            })

        resjson = {
            "ret": True,
            "status": "success",
            "msg": "ok",
            "data": {
                "system": system
            }
        }

        return HttpResponse(json.dumps(resjson), content_type='application/json')



@accept_websocket
def ChatWebsocket(request):
    print(request.user)
    if not request.is_websocket():  # 判断是不是websocket连接
        try:  # 如果是普通的http方法
            message = request.GET['message']
            return HttpResponse(message)
        except:
            resjson = {
                "ret": True,
                "status": "fail",
                "msg": "非法websocket连接"
            }
            return HttpResponse(json.dumps(resjson), content_type='application/json')
    else:
        if not request.user.id:
            resjson = {
                "ret": True,
                "status": "notLogin",
                "msg": "用户未登录"
            }
            return request.websocket.send(str.encode(str(resjson)))  # 发送消息到客户端

        for message in request.websocket:
            msg = json.loads(message)
            chatRoomLi = chatRoom.objects.get(id=int(msg['id']))
            chatRecordSave = chatRecord()
            chatRecordSave.chatRoom = chatRoomLi
            chatRecordSave.currentUser = request.user
            chatRecordSave.content = msg['content']
            chatRecordSave.save()
            resjson = {
                "ret": True,
                "status": "success",
                "msg": "ok"
            }
            request.websocket.send(str.encode(str(resjson)))  # 发送消息到客户端